/*
 *  Copyright (C) 2007 Daniel Jackson <carpman@voidptr.org>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA.
 *
 *  Author : Daniel Jackson <carpman@voidptr.org>
*/

using System;
using System.Text;
using System.Security.Permissions;
using Microsoft.Win32;

namespace PortaMIME
{
    /// <summary>
    /// Windows MIME type back end. Uses the Windows registry to retrieve MIME information.
    /// </summary>
    public class WindowsRegistrySource : TypeDatabaseSource
    {
        protected RegistryPermission regPermission;
        protected RegistryKey classesRoot;
        protected RegistryKey typeKey;

        public WindowsRegistrySource()
        {
            regPermission = new RegistryPermission(RegistryPermissionAccess.Read, "\\\\HKEY_CLASSES_ROOT");
            classesRoot = Registry.ClassesRoot;
            typeKey = classesRoot.OpenSubKey("MIME\\Database\\Content Type");
        }

        #region TypeDatabaseSource Members

        public MIMEType getTypeForExtension(string extension)
        {
            MIMEType outType = null;

            foreach(string keyname in typeKey.GetSubKeyNames())
            {
                RegistryKey currentKey = classesRoot.OpenSubKey("MIME\\Database\\Content Type\\"+keyname);
                if ((string)currentKey.GetValue("Extension") == extension)
                {
                    outType = new MIMEType();
                    outType.typeString = keyname;
                }
            }
            return outType;
        }

        public string[] getExtensionForType(MIMEType type)
        {
            foreach (string keyname in typeKey.GetSubKeyNames())
            {
                if (keyname == type.typeString)
                {
                    RegistryKey currentKey = classesRoot.OpenSubKey("MIME\\Database\\Content Type\\" + keyname);
                    return new string[] {(string)currentKey.GetValue("Extension")};
                }
            }

            return null;
        }

        #endregion
    }
}
